package com.smile.ye.common.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smile.ye.response.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        System.out.println("账号密码错误");
        String message = exception.getMessage();
        if(exception instanceof BadCredentialsException) message = "账号或密码错误";
        response.setContentType("application/json;charset=UTF-8");
        String string = new ObjectMapper().writeValueAsString(Result.fail(500,message));
        response.getWriter().println(string);
    }
}
